package zss.weibo.tqq;

import org.apache.http.*;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Lookup;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.impl.cookie.DefaultCookieSpecProvider;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by gavin on 15-7-23.
 */
public class HttpClientTest {

	public static void main(String[] args) {
		// 创建一个HttpClient
		RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
		CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
		try {
			
			String qua = "AMB_612/061348&NA/061348&android7.0&6711214&FRDAL00&NA&NA&V3";
			String netType = "1";
			String terminal = "862679033397686&00000000-3d8a-a17d-4627-486f0001bcd7&a4:71:74:71:fc:b7&NA";
			String pageType = "1";
			String guestAccount = "FangWenShan7887";
			String lastMsgId = "474897014510778";
			String lastMsgTimestamp = "1367537062";
			String pageFlag = "1";
			String pageSize = "10";
			String contentType = "0";
			String msgType = "0";

			// 构造post数据
			List<NameValuePair> valuePairs = new LinkedList<NameValuePair>();
			valuePairs.add(new BasicNameValuePair("qua", qua));
			valuePairs.add(new BasicNameValuePair("netType", netType));
			valuePairs.add(new BasicNameValuePair("terminal", terminal));
			valuePairs.add(new BasicNameValuePair("pageType", pageType));
			valuePairs.add(new BasicNameValuePair("guestAccount", guestAccount));
			valuePairs.add(new BasicNameValuePair("lastMsgId", lastMsgId));
			valuePairs.add(new BasicNameValuePair("lastMsgTimestamp", lastMsgTimestamp));
			valuePairs.add(new BasicNameValuePair("pageFlag", pageFlag));
			valuePairs.add(new BasicNameValuePair("pageFlag", pageFlag));
			valuePairs.add(new BasicNameValuePair("pageSize", pageSize));
			valuePairs.add(new BasicNameValuePair("contentType", contentType));
			valuePairs.add(new BasicNameValuePair("msgType", msgType));
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, Consts.UTF_8);

			String postUrl = "http://r.t.qq.com/cbdata/message/broadcast";
			// 创建一个post请求
			HttpPost post = new HttpPost(postUrl);
			post.setHeader("Cookie",
					"p_uin=o826242827;p_skey=pZVwCmxQcM-PDLHJKjPcUdgw8-9iPMHn0jtokB1E7Uc_");

			// 注入post数据
			post.setEntity(entity);
			HttpResponse httpResponse = httpClient.execute(post);
			// 打印登录是否成功信息
			printResponse(httpResponse);

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void printResponse(HttpResponse httpResponse) throws ParseException, IOException {
		// 获取响应消息实体
		HttpEntity entity = httpResponse.getEntity();
		// 响应状态
		System.out.println("status:" + httpResponse.getStatusLine());
		System.out.println("headers:");
		HeaderIterator iterator = httpResponse.headerIterator();
		while (iterator.hasNext()) {
			System.out.println("\t" + iterator.next());
		}
		// 判断响应实体是否为空
		if (entity != null) {
			String responseString = EntityUtils.toString(entity);
			System.out.println("response length:" + responseString.length());
			System.out.println("response content:" + responseString.replace("\r\n", ""));
		}
	}

	public static Map<String, String> cookieMap = new HashMap<String, String>(64);

	// 从响应信息中获取cookie
	public static String setCookie(HttpResponse httpResponse) {
		System.out.println("----setCookieStore");
		Header headers[] = httpResponse.getHeaders("Set-Cookie");
		if (headers == null || headers.length == 0) {
			System.out.println("----there are no cookies");
			return null;
		}
		String cookie = "";
		for (int i = 0; i < headers.length; i++) {
			cookie += headers[i].getValue();
			if (i != headers.length - 1) {
				cookie += ";";
			}
		}

		String cookies[] = cookie.split(";");
		for (String c : cookies) {
			c = c.trim();
			if (cookieMap.containsKey(c.split("=")[0])) {
				cookieMap.remove(c.split("=")[0]);
			}
			cookieMap.put(c.split("=")[0],
					c.split("=").length == 1 ? "" : (c.split("=").length == 2 ? c.split("=")[1] : c.split("=", 2)[1]));
		}
		System.out.println("----setCookieStore success");
		String cookiesTmp = "";
		for (String key : cookieMap.keySet()) {
			cookiesTmp += key + "=" + cookieMap.get(key) + ";";
		}

		return cookiesTmp.substring(0, cookiesTmp.length() - 2);
	}
}